<template>
  <div class="map-container">
    <div id="map"></div>
    <div id="location" @click="location">标记</div>
    <div class="search-warp">
      <div class="input-warp">
        <input id="search-input" type="text" v-model="searchValue" />
        <div id="search" @click="search"></div>
      </div>
      <ul  class="search-result">
        <li
          v-for="(item, index) in searchArr"
          :key="index"
          class="search-row" 
          :title="item.properties.NAME"
          v-text="item.properties.NAME"
          @click="searchResultItemClick(item)"
        ></li>
      </ul>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import { setDefaultOptions, loadCss, loadModules } from "esri-loader";
import mark from '../assets/images/mark.png'
export default {
  name: 'MapComponent',
  props: {
    geometry: {
      type: Array,
      default () {
        return []
      }
    },
    geometryData: {
      type: Array,
      default () {
        return []
      }
    },
  },
  data() {
    return {
      mark, // 标记图片
      searchValue: '', // 查询内容,
      timer: null, // 节流监听
      isSearch: false, // 是否查询
      mapCenter: [119.1452988669041, 36.73061587299328],// 中心点
      mapZoom: 3, // map的缩放等级
      api: { // api 地址
        js: 'https://js.arcgis.com/3.33/',
        css: 'https://js.arcgis.com/3.33/esri/css/esri.css',
        geometryServiceUrl: 'http://124.128.48.217:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer'
      },
      wmtsOption: { // wmts 参数
        url: "http://10.88.47.243:8000/wmts/SBKJSJ201901",
        identifier: "SBKJSJ201901",
        tileMatrixSet: "TileMatrixSet_0",
        wkid: 4490,
        extent: {
          xmin: 117.812133,
          ymin: 35.567721,
          xmax: 120.349032,
          ymax: 37.336641
        }
      },
      searchUrl: 'http://10.88.47.242:8099/newmap/rest/services/dmdz/wfdmdz/FeatureServer',
      searchArr: null,
      map: null,
      tb: null,
      picSymbol: null,
      polygonSymbol: null,
      polylineSymbol: null,
      infoTemplate: null,
      // api通用
      apiPoint: null,
      apiPolygon: null,
      apiPolyline: null,
      apiGraphic: null,
      apiSpatialReference: null,
      apiMultipoint: null,
      apiGeometryService: null
    }
  },
  watch: {
    geometry (val) {
      // 清除graphic
      this.map.graphics.clear();
      let pointArr = [];
      let rings = [];
      val.map(item => {
        pointArr.push(new this.apiPoint(item[0], item[1], new this.apiSpatialReference(4549)));
      })
      this.apiGeometryService.project(pointArr, new this.apiSpatialReference(4490), result => {
        console.log(result);
        result.map(item => {
          rings.push([item.x, item.y]);
        })
        // Polygon
        let geometryPolygon = this.apiPolygon(this.map.spatialReference);
        geometryPolygon.addRing(rings);
        // Polyline
        let geometryPolyline = this.apiPolyline(this.map.spatialReference);
        geometryPolyline.addPath(rings);
        let geometryGraphic = new this.apiGraphic(geometryPolyline, this.polylineSymbol);
        // 添加多边形并定位
        this.map.graphics.add(geometryGraphic);
        this.map.setExtent(geometryPolygon.getExtent().expand(4))
        this.$emit("getgeometryData", JSON.stringify(rings))
      });
    },
    geometryData (val) {
        this.map.graphics.clear();
         // Polygon
        let geometryPolygon = this.apiPolygon(this.map.spatialReference);
        geometryPolygon.addRing(val);
        // Polyline
        let geometryPolyline = this.apiPolyline(this.map.spatialReference);
        geometryPolyline.addPath(val);
        let geometryGraphic = new this.apiGraphic(geometryPolyline, this.polylineSymbol);
        // 添加多边形并定位
        this.map.graphics.add(geometryGraphic);
        this.map.setExtent(geometryPolygon.getExtent().expand(4));
        
    },
    searchValue: {
      handler() {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.handleFormSearch();
        }, 200)
      },
      deep: true
    }
  },
  created() {
    this.createMap();
  },
  methods: {
    location () {
      this.map.disableMapNavigation();
      this.tb.activate("point");
    },
    search () {
      this.isSearch = true;
      this.searchValue = this.searchValue.trim('');
      if (this.searchValue !== '') {
        this.searchList();
      } else {
        this.searchArr = [];
        this.map.graphics.clear();
        this.map.infoWindow.hide();
      }
    },
    handleFormSearch () {
      this.searchValue = this.searchValue.trim('');
      if (this.searchValue !== '') {
        this.searchList();
      } else {
        this.searchArr = [];
        this.map.graphics.clear();
        this.map.infoWindow.hide();
      }
    },
    searchResultItemClick ({ properties }) {
      this.searchValue = properties.NAME;
      console.log(properties);
      this.map.graphics.clear();
      let attr = { 
        "NAME": properties.NAME,
        "ADMINNAME": properties.ADMINNAME,
        "ADDRESS": properties.ADDRESS,
        "OLDADDRESS": properties.OLDADDRESS 
      };
      let itempoint = new this.apiPoint(properties.ZBX, properties.ZBY,
        new this.apiSpatialReference({ wkid: this.wmtsOption.wkid }));

      let graphic = new this.apiGraphic(itempoint, this.picSymbol, attr, this.infoTemplate);
      this.map.graphics.add(graphic);
      this.map.infoWindow.show(itempoint);
      this.map.infoWindow.setFeatures([graphic]);
      this.map.centerAt(itempoint);
    },
    searchList () {
      axios({
        url: `${this.searchUrl}/query?&layer=wfdmdz&geotype=point&geo=&srsin=&where="NAME" LIKE '%${this.searchValue}%'&page=1&maxitems=5&fieldsout=*&text=&sortmode=0&sortfield=&format=json`
      }).then(({ data }) => {
        console.log(data);
        this.searchArr = [];
        if (this.searchValue === '' || !data.content || !data.content.features.features) {
          this.searchArr = [];
          return
        }
        // 查询结果
        this.searchArr = data.content.features.features;

        // 显示查询图标
        if (this.isSearch) {
          this.map.graphics.clear();
          let multiPoint = new this.apiMultipoint(
            new this.apiSpatialReference({ wkid: this.wmtsOption.wkid }));

          this.searchArr.map(({ properties }) => {
            let attr = {
              "NAME": properties.NAME,
              "ADMINNAME": properties.ADMINNAME,
              "ADDRESS": properties.ADDRESS,
              "OLDADDRESS": properties.OLDADDRESS
            };
            let point = new this.apiPoint(properties.ZBX, properties.ZBY,
              new this.apiSpatialReference({ wkid: this.wmtsOption.wkid }));

            this.map.graphics.add(new this.apiGraphic(point, this.picSymbol, attr, this.infoTemplate));
            multiPoint.addPoint(point);
          })
          this.map.setExtent(multiPoint.getExtent().expand(4));
        }
        this.isSearch = false;
      })
      
    },
    createMap () {
      // 设置指定api
      setDefaultOptions({ url: this.api.js })
      loadCss(this.api.css);

      loadModules(["esri/map",
        "esri/InfoTemplate",
        "esri/layers/WMTSLayer",
        "esri/layers/WMTSLayerInfo",
        "esri/geometry/Extent",
        "esri/geometry/Point",
        "esri/geometry/Multipoint",
        "esri/geometry/Polygon",
        "esri/geometry/Polyline",
        "esri/layers/TileInfo",
        "esri/SpatialReference",
        "esri/toolbars/draw",
        "esri/symbols/PictureMarkerSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/tasks/GeometryService",
        "esri/Color",
        "esri/graphic",
        "dojo/parser"])
      .then(([Map, InfoTemplate, WMTSLayer, WMTSLayerInfo, Extent, Point, Multipoint, Polygon,
        Polyline, TileInfo, SpatialReference,  Draw, PictureMarkerSymbol,
        SimpleFillSymbol, SimpleLineSymbol, GeometryService, 
        Color, Graphic, parser]) => {
        parser.parse();
        // api通用
        this.apiPoint = Point;
        this.apiGraphic = Graphic;
        this.apiSpatialReference = SpatialReference;
        this.apiMultipoint = Multipoint;
        this.apiPolygon = Polygon;
        this.apiPolyline = Polyline;
        this.apiGeometryService = new GeometryService(this.api.geometryServiceUrl);

        this.picSymbol = new PictureMarkerSymbol(this.mark, 32, 32);

        this.polygonSymbol = new SimpleFillSymbol(
                    SimpleFillSymbol.STYLE_SOLID,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID, new Color([0, 191, 255, 0.6]), 2), new Color([237, 90, 139, 1]));
       
        this.polylineSymbol =new SimpleLineSymbol(
          SimpleLineSymbol.STYLE_SOLID,
          new Color([255,0,0]),
          3
        );
        
        this.infoTemplate = new InfoTemplate("${NAME}", 
        "所在县区: ${ADMINNAME} <br/>" +
        "所在地址: ${OLDADDRESS} <br/>" +
        "所在地址: ${ADDRESS}");

        this.map = new Map("map", {
          center: this.mapCenter,
          zoom: this.mapZoom
        });
        
        this.map.on('click', (e) => {
          console.log(e);
        })

        let dzdtWMTS = getWMTSLayer(this.wmtsOption);
        this.map.addLayer(dzdtWMTS);

        // 标记事件
        this.tb = new Draw(this.map);
        this.tb.on("draw-end", evt => {
          this.tb.deactivate();
          this.map.enableMapNavigation();
          this.map.graphics.add(new Graphic(evt.geometry, this.picSymbol));
          this.$emit('mark', evt.geometry)
        });


      // 加载WMTS图层
      function getWMTSLayer(options) {
        let tileInfo = new TileInfo({
          "dpi": 96,
          "format": "image/png",
          "compressionQuality": 0,
          "spatialReference": new SpatialReference({
            "wkid": options.wkid
          }),
          "rows": 256,
          "cols": 256,
          "origin": {
            "x": -180,
            "y": 90
          },
          "lods": [{
            "level": "0", "scale": 1155583.916016, "resolution": 0.703125
          }, {
            "level": "1", "scale": 577791.958008, "resolution": 0.3515625
          }, {
            "level": "2", "scale": 288895.979004, "resolution": 0.17578125
          }, {
            "level": "3", "scale": 144447.989502, "resolution": 0.087890625
          }, {
            "level": "4", "scale": 72223.994751, "resolution": 0.0439453125
          }, {
            "level": "5", "scale": 36111.997375, "resolution": 0.02197265625
          }, {
            "level": "6", "scale": 18055.998688, "resolution": 0.010986328125
          }, {
            "level": "7", "scale": 9027.999344, "resolution": 0.0054931640625
          }, {
            "level": "8", "scale": 4513.999672, "resolution": 0.00274658203125
          }, {
            "level": "9", "scale": 2256.999836, "resolution": 0.001373291015625
          }, {
            "level": "10", "scale": 1128.499918, "resolution": 0.0006866455078125
          }, {
            "level": "11", "scale": 564.249959, "resolution": 0.00034332275390625
          }]
        });
        let tileExtent = new Extent(
          options.extent.xmin, options.extent.ymin,
          options.extent.xmax, options.extent.ymax,
          new SpatialReference({ wkid: options.wkid }));

        let layerInfo = new WMTSLayerInfo({
          tileInfo: tileInfo,
          fullExtent: tileExtent,
          initialExtent: tileExtent,
          identifier: options.identifier,
          tileMatrixSet: options.tileMatrixSet,
          format: "png",
          style: "default"
        });

        let resourceInfo = {
          version: "1.0.0",
          layerInfos: [layerInfo],
          copyright: ""
        };

        let option = {
          serviceMode: "KVP",
          resourceInfo: resourceInfo,
          layerInfo: layerInfo
        };
        let wmtsLayer = new WMTSLayer(options.url, option);
        return wmtsLayer;
      }

      })
      .catch(err => {
        // handle any script or module loading errors
        console.error(err);
      });
        }
  },
}
</script>
<style scoped>
.map-container {
  position: relative;
  height: 100%;
}
#map {
  height: 100%;
}
#location {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 5px 10px;
  border-radius: 5px;
  background: #3385ff;
  color: #ffffff;
  cursor: pointer;
}
.search-warp {
  position: absolute;
  top: 20px;
  left: 70px;
  width: 300px;
  height: 35px;
  background-color: #ffffff;
}
.input-warp {
  display: flex;
  width: 300px;
  height: 35px;
  box-shadow: 1px 1px 2px 0 #cccccc;
  border-radius: 3px;
  overflow: hidden;
}
.input-warp input {
  flex: 1;
  outline: none;
  border: none;
  font-size: 14px;
  text-indent: 10px ;
}
#search {
  width: 57px;
  height: 35px;
  background: #3385ff;
  background-image: url('../assets/images/search.png');
  background-position: center;
  background-repeat: no-repeat;
  background-size: 30px 30px;
  cursor: pointer;
}
.search-result {
  position: absolute;
  top: 42px;
  left: 0;
  list-style: none;
  background: #ffffff;
  box-shadow: 1px 1px 2px 0 #cccccc;
}
.search-row {
  width: 300px;
  height: 30px;
  padding-right: 10px;
  font-size: 14px;
  text-indent: 8px;
  line-height: 30px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.search-row:hover {
  cursor: pointer;
  background-color: #cccccc;
}

</style>